<template>
  <div class='big'>
    <div class='login'>
      <h1 class='title'>{{ title }}</h1>
      <div class='logins centered-content'>
        <div class="centered-container">
          <input 
            v-model="email"
            type="email"
            placeholder="邮箱账号"
            class="account-input"
            @blur="validateEmail"
          >
        </div>  
        <div class="verify-container">
          <input 
            v-model="password"
            type="password"
            placeholder="密码"
            class="verify-input"
            @blur="validatePassword"
          >
        </div>
        <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>
        
        <button 
          @click="handleLogin"
          :disabled="loading || !email || !password || !agreed"
          class='button'
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </div>
    </div>
    <div class='small'>
      <span @click="goToRegister">注册</span>
      /
      <span @click="goToForgotPassword">忘记密码</span>
    </div>
    <div class='bottom'>
      <div class='threelogin'>
        <img 
          :src="appleIconPath" 
          alt="苹果登录"
          @click="qqLogin"
          class="cursor-pointer"
        >
        <img 
          :src="wechatIconPath" 
          alt="微信登录"
          @click="wechatLogin"
          class="cursor-pointer"
        >
      </div>
      <p class='check'>
        <input type="checkbox" v-model="agreed">
        <a :href="userAgreementLink" :style="agreementLinkStyle">同意《用户协议》，《隐私条款》</a>后方可登录
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const title = ref('爱韵动-登录');
const email = ref('');
const password = ref('');
const loading = ref(false);
const agreed = ref(false);
const errorMsg = ref('');
const blinkAgreement = ref(false);
const router = useRouter();

// 后端API地址
const API_BASE_URL = 'http://localhost:3000';

// 邮箱验证正则表达式：必须以@qq.com结尾
const emailRegExp = /^[^@]+@qq\.com$/;

// 用户协议链接样式
const agreementLinkStyle = computed(() => ({
  color: blinkAgreement.value ? '#ff0000' : '#000000',
  textDecoration: blinkAgreement.value ? 'underline' : 'none',
  animation: blinkAgreement.value ? 'blink 1s infinite' : 'none'
}));

// 监听邮箱和密码输入
watch([email, password], ([newEmail, newPassword]) => {
  if (newEmail && newPassword && !agreed.value) {
    startBlinking();
  } else {
    stopBlinking();
  }
});

// 开始闪烁
const startBlinking = () => {
  blinkAgreement.value = true;
};

// 停止闪烁
const stopBlinking = () => {
  blinkAgreement.value = false;
};

// 添加闪烁动画样式
const style = document.createElement('style');
style.textContent = `
@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}
`;
document.head.appendChild(style);

// 登录处理函数
const handleLogin = async () => {
  if (!agreed.value) {
    ElMessage.warning('请勾选用户协议');
    return;
  }

  if (!validateEmail() || !validatePassword()) {
    return;
  }
  
  loading.value = true;
  
  try {
    const response = await axios.post(`${API_BASE_URL}/login`, {
      email: email.value,
      password: password.value
    });
    
    if (response.data.code === 200) {
      // 存储token和用户信息
      const token = response.data.token;
      localStorage.setItem('token', token);
      localStorage.setItem('userEmail', email.value);
      
      // 登录成功后获取完整用户信息
      try {
        const userInfoResponse = await axios.get(`${API_BASE_URL}/getlogin`, {
          timeout: 10000
        });
        
        if (userInfoResponse.data.code === 200 && userInfoResponse.data.data && userInfoResponse.data.data.length > 0) {
          // 存储完整的用户信息到localStorage
          const currentUser = userInfoResponse.data.data.find(user => user.email === email.value) || userInfoResponse.data.data[0];
          localStorage.setItem('currentUser', JSON.stringify(currentUser));
          console.log('用户信息已存储:', currentUser);
        }
      } catch (userInfoError) {
        console.warn('获取用户详细信息失败，但登录成功:', userInfoError);
      }
      
      ElMessage.success('登录成功');
      // 跳转到check页面
      router.push('/check');
    } else {
      ElMessage.error(response.data.msg || '登录失败，请重试');
    }
  } catch (error: any) {
    console.error('登录请求错误:', error);
    ElMessage.error(error.response?.data?.msg || '登录失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 邮箱验证函数
const validateEmail = () => {
  if (!email.value) {
    ElMessage.warning('请输入邮箱');
    return false;
  }
  
  if (!emailRegExp.test(email.value)) {
    ElMessage.warning('请使用@qq.com邮箱');
    return false;
  }
  
  return true;
};

// 密码验证函数
const validatePassword = () => {
  if (!password.value) {
    ElMessage.warning('请输入密码');
    return false;
  }
  
  if (password.value.length < 6) {
    ElMessage.warning('密码至少6位');
    return false;
  }
  
  return true;
};

// 第三方登录方法
const wechatLogin = async () => {
  if (!agreed.value) {
    ElMessage.warning('请勾选用户协议');
    return;
  }

  ElMessage.info('正在通过微信登录并更新用户信息...');
  try {
    // 定义要更新的用户信息
    const targetEmail = '1514992092@qq.com';
    const updateData = {
      email: targetEmail,       // 目标用户邮箱
      name: '王紫冰',           // 要更新的name字段
      img: '../1.jpg'           // 可选：同时更新头像
    };
    
    console.log('发送到update-password的参数:', updateData);
    
    // 调用更新接口修改用户name字段
    const updateRes = await axios.post(`${API_BASE_URL}/update-password`, updateData);
    
    // 检查更新结果
    if (updateRes.data.code === 200) {
    } else {
      ElMessage.warning('用户信息更新失败，但继续登录流程');
    }
    
    console.log('update-password接口响应:', updateRes.data);
    
    // 继续微信登录流程
    const res = await axios.get("/api", {
      params: {
        act: "login",
        appid: "3521",
        appkey: "a010aaf9582fe1587b08b283a47ca14b",
        type: "wx",
        redirect_uri: "http://127.0.0.1:5173/check",
      },
    });
    sessionStorage.setItem("longtermToken", "hhhhnxsm");
    window.open(res.data.url, "_self");
  } catch (error: any) {
    console.error('微信登录过程中发生错误:', error);
    
    // 区分网络错误和业务错误
    if (error.response) {
      ElMessage.error(`接口错误: ${error.response.data.msg || '请检查参数'}`);
      console.log('接口响应数据:', error.response.data);
    } else {
      ElMessage.error('网络错误，请检查您的网络连接');
    }
  }
};


const qqLogin = async () => {
  if (!agreed.value) {
    ElMessage.warning('请勾选用户协议');
    return;
  }

  ElMessage.info('正在跳转至QQ登录...');
  try {
    const res = await axios.get("https://api.example.com/api", {
      params: {
        act: "login",
        appid: "3521",
        appkey: "a010aaf9582fe1587b08b283a47ca14b",
        type: "qq",
        redirect_uri: "http://127.0.0.1:5173/check",
      },
    });
    sessionStorage.setItem("longtermToken", "hhhhnxsm");
    window.open(res.data.url, "_self");
  } catch (error) {
    console.error('QQ登录失败', error);
    ElMessage.error('QQ登录失败，请重试');
  }
};

const goToRegister = () => {
  router.push('/zhuce');
};

const goToForgotPassword = () => {
  router.push('/lost');
};

const wechatIconPath = '../wx.png';
const appleIconPath = '../QQ.png';
const userAgreementLink = '#';
const privacyPolicyLink = '#';
</script>

<style scoped>
/* 样式保持不变 */
.threelogin{
  display:flex;
  justify-content:center;
}
.threelogin img{
  width:10%;
  margin:0% 5%;
}
.button{
  width:70%;
  border-radius:50px;
  background-color:#54EA8C;
  border:0px;
  font-size:20px;
  margin-top: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
.check{
  padding:0% 16%;
  float:left;
  text-align:left;
  font-size:12px;
}
.title {
  font-style: italic; 
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
  letter-spacing: 0.5px; 
  font-size:55px;
  font-weight:800;
  text-align: center;
}
.login{
  padding-top:20vh;
}
.logins{
  padding-top:3vh;
  line-height:7vh;
}
.big {
  width:100%;
  height:100vh;
  background: linear-gradient(to bottom,hsl(182, 100.00%, 83.70%) 0%,white 100%);
}
.bottom{
  margin-top:25vh;
}

.account-input{
  width: 70%;
  font-size: 16px;
  border:0px;
  height:5vh;
  background-color:#CBFEFF;
  padding: 0 10px;
  border-radius: 4px;
}
.verify-input {
  width: 70%;
  font-size: 16px;
  border:0px;
  height:5vh;
  background-color:#D3FDFF;
  padding: 0 10px;
  border-radius: 4px;
}

.verify-container {
  width:70%;
  border-bottom:0.1px solid #ccc;
}

.error-message {
  color: #e53935;
  font-size: 14px;
  margin-bottom: 10px;
}

.centered-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.centered-container {
  width:70%;
  border-bottom:0.1px solid #ccc;
  margin-bottom: 15px;
}
.small{
  width:70%;
  margin:0 auto;
  text-align:right;
  margin-top:5%;
  cursor: pointer;
}
</style>